/*
 * Copyright 2012 Faculty of Informatics - Masaryk University.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.pa165.creatures.dao.web.impl;

import cz.muni.fi.pa165.creatures.dao.utils.DAOUtils;
import cz.muni.fi.pa165.creatures.dao.web.PersonDAO;
import cz.muni.fi.pa165.creatures.model.web.Person;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 * This class represents the implementation of all basic operations upon
 * {@link cz.muni.fi.pa165.creatures.model.web.Person} instances.
 *
 * @author xmiklos1
 */
@Repository
@Transactional
public class PersonDAOImpl implements PersonDAO {

    @PersistenceContext
    EntityManager em;

    @Override
    public Long create(Person person) {
        DAOUtils.notNull(person);
        em.persist(person);
        return person.getId();
    }

    @Override
    public void update(Person person) {
        DAOUtils.notNull(person);
        em.merge(person);
    }

    @Override
    public void remove(Person person) {
        DAOUtils.notNull(person);
        em.remove(person);
    }

    @Override
    public Person get(Long id) {
        DAOUtils.notNull(id);
        return em.find(Person.class, id);
    }

    @Override
    public Long getCount() {
        return (Long) em.createQuery("select count(p) from Person as p")
                .getSingleResult();
    }

    @Override
    public List<Person> getAll() {
        return em.createQuery("from Person").getResultList();
    }

    @Override
    public void removeAll() {
        em.createQuery("delete from Person p").executeUpdate();
    }

    @Override
    public Person getByName(String name) {
        DAOUtils.notNull(name);
        Query q = em.createQuery("select p from Person as p "
                + "where p.name = :name");
        q.setParameter("name", name);
        try {
            return (Person) q.getResultList().get(0);
        } catch (IndexOutOfBoundsException ex) {
            return null;
        }
    }
}
